{% extends "base.html" %}

{% block title %}AI智能报告生成 - {{ app_name }}{% endblock %}

{% block page_title %}AI智能报告生成{% endblock %}

{% block page_subtitle %}利用先进的人工智能技术，自动生成高质量的分析报告{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 快速操作区 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <!-- 日报生成 -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover cursor-pointer" onclick="showDailyReportModal()">
            <div class="flex items-center justify-between mb-4">
                <div class="bg-blue-100 p-3 rounded-full">
                    <i class="fas fa-calendar-day text-blue-600 text-xl"></i>
                </div>
                <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">AI</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">智能日报</h3>
            <p class="text-gray-600 text-sm">基于当日数据自动生成分析日报</p>
        </div>

        <!-- 周报生成 -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover cursor-pointer" onclick="showWeeklyReportModal()">
            <div class="flex items-center justify-between mb-4">
                <div class="bg-purple-100 p-3 rounded-full">
                    <i class="fas fa-calendar-week text-purple-600 text-xl"></i>
                </div>
                <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">AI</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">智能周报</h3>
            <p class="text-gray-600 text-sm">周度数据分析和趋势预测报告</p>
        </div>

        <!-- 月报生成 -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover cursor-pointer" onclick="showMonthlyReportModal()">
            <div class="flex items-center justify-between mb-4">
                <div class="bg-indigo-100 p-3 rounded-full">
                    <i class="fas fa-calendar-alt text-indigo-600 text-xl"></i>
                </div>
                <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">AI</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">智能月报</h3>
            <p class="text-gray-600 text-sm">月度综合分析和战略建议报告</p>
        </div>

        <!-- 自定义报告 -->
        <div class="bg-white rounded-lg shadow-md p-6 card-hover cursor-pointer" onclick="showCustomReportModal()">
            <div class="flex items-center justify-between mb-4">
                <div class="bg-green-100 p-3 rounded-full">
                    <i class="fas fa-file-alt text-green-600 text-xl"></i>
                </div>
                <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">AI</span>
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">自定义报告</h3>
            <p class="text-gray-600 text-sm">根据需求定制专项分析报告</p>
        </div>
    </div>

    <!-- AI报告模板 -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-8">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-semibold text-gray-800">AI报告模板</h2>
            <button class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors" onclick="loadAITemplates()">
                <i class="fas fa-sync-alt mr-2"></i>刷新模板
            </button>
        </div>
        <div id="aiTemplates" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <!-- 模板卡片将在这里动态加载 -->
        </div>
    </div>

    <!-- 报告列表 -->
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-xl font-semibold text-gray-800">我的报告</h2>
            <div class="flex space-x-2">
                <select id="reportTypeFilter" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">全部类型</option>
                    <option value="daily">日报</option>
                    <option value="weekly">周报</option>
                    <option value="monthly">月报</option>
                    <option value="custom">自定义</option>
                </select>
                <select id="reportStatusFilter" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">全部状态</option>
                    <option value="generating">生成中</option>
                    <option value="completed">已完成</option>
                    <option value="failed">失败</option>
                </select>
                <button class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors" onclick="loadReports()">
                    <i class="fas fa-search mr-2"></i>查询
                </button>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full table-auto">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报告标题</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody id="reportsTableBody" class="bg-white divide-y divide-gray-200">
                    <!-- 报告列表将在这里动态加载 -->
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div id="pagination" class="mt-4 flex justify-center">
            <!-- 分页控件将在这里动态加载 -->
        </div>
    </div>
</div>

<!-- 日报生成模态框 -->
<div id="dailyReportModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">生成AI智能日报</h3>
                    <button onclick="hideModal('dailyReportModal')" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <form id="dailyReportForm">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">报告日期</label>
                        <input type="date" id="dailyReportDate" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="hideModal('dailyReportModal')" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                        <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">生成报告</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 周报生成模态框 -->
<div id="weeklyReportModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">生成AI智能周报</h3>
                    <button onclick="hideModal('weeklyReportModal')" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <form id="weeklyReportForm">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">周开始日期</label>
                        <input type="date" id="weeklyReportDate" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="hideModal('weeklyReportModal')" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                        <button type="submit" class="px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600">生成报告</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 月报生成模态框 -->
<div id="monthlyReportModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">生成AI智能月报</h3>
                    <button onclick="hideModal('monthlyReportModal')" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <form id="monthlyReportForm">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">年份</label>
                        <select id="monthlyReportYear" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <!-- 年份选项将动态生成 -->
                        </select>
                    </div>
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">月份</label>
                        <select id="monthlyReportMonth" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="1">1月</option>
                            <option value="2">2月</option>
                            <option value="3">3月</option>
                            <option value="4">4月</option>
                            <option value="5">5月</option>
                            <option value="6">6月</option>
                            <option value="7">7月</option>
                            <option value="8">8月</option>
                            <option value="9">9月</option>
                            <option value="10">10月</option>
                            <option value="11">11月</option>
                            <option value="12">12月</option>
                        </select>
                    </div>
                    
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="hideModal('monthlyReportModal')" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                        <button type="submit" class="px-4 py-2 bg-indigo-500 text-white rounded-md hover:bg-indigo-600">生成报告</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 自定义报告生成模态框 -->
<div id="customReportModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="bg-white rounded-lg shadow-xl max-w-lg w-full">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">生成AI智能自定义报告</h3>
                    <button onclick="hideModal('customReportModal')" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <form id="customReportForm">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">报告标题</label>
                        <input type="text" id="customReportTitle" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
                            <input type="date" id="customReportStartDate" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
                            <input type="date" id="customReportEndDate" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">分析章节</label>
                        <div class="space-y-2">
                            <label class="flex items-center">
                                <input type="checkbox" value="overview" checked class="mr-2">
                                <span class="text-sm">总体概述</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" value="trends" checked class="mr-2">
                                <span class="text-sm">趋势分析</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" value="geo_analysis" checked class="mr-2">
                                <span class="text-sm">地理分析</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" value="category_analysis" checked class="mr-2">
                                <span class="text-sm">分类分析</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" value="key_issues" checked class="mr-2">
                                <span class="text-sm">重点问题</span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="hideModal('customReportModal')" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                        <button type="submit" class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600">生成报告</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 报告详情模态框 -->
<div id="reportDetailModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div class="p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">报告详情</h3>
                    <button onclick="hideModal('reportDetailModal')" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div id="reportDetailContent">
                    <!-- 报告详情将在这里动态加载 -->
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 全局函数定义 - 兼容性包装
    function showToast(message, type = 'info') {
        if (window.uxUtils && window.uxUtils.showToast) {
            window.uxUtils.showToast(message, type);
        } else {
            // 降级处理
            console.log(`[${type}] ${message}`);
            alert(message);
        }
    }

    function showLoading(message = '加载中...') {
        if (window.uxUtils && window.uxUtils.showLoading) {
            window.uxUtils.showLoading('global', message);
        } else {
            console.log(`Loading: ${message}`);
        }
    }

    function hideLoading() {
        if (window.uxUtils && window.uxUtils.hideLoading) {
            window.uxUtils.hideLoading('global');
        } else {
            console.log('Loading hidden');
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化认证管理器
        if (window.authManager) {
            window.authManager.checkLoginStatus();
        }
        
        // 加载页面数据
        loadAITemplates();
        loadReports();
        initializeDateInputs();
    });

    // 初始化日期输入框
    function initializeDateInputs() {
        const today = new Date();
        
        // 设置日报日期默认为今天
        const dailyDateInput = document.getElementById('dailyReportDate');
        if (dailyDateInput) {
            dailyDateInput.value = today.toISOString().split('T')[0];
        }
        
        // 设置周报日期默认为本周一
        const weeklyDateInput = document.getElementById('weeklyReportDate');
        if (weeklyDateInput) {
            const monday = new Date(today);
            monday.setDate(today.getDate() - today.getDay() + 1);
            weeklyDateInput.value = monday.toISOString().split('T')[0];
        }
        
        // 设置月报年份和月份默认为今年本月
        const yearSelect = document.getElementById('monthlyReportYear');
        const monthSelect = document.getElementById('monthlyReportMonth');
        if (yearSelect && monthSelect) {
            const currentYear = today.getFullYear();
            for (let year = currentYear - 2; year <= currentYear + 2; year++) {
                const option = document.createElement('option');
                option.value = year;
                option.textContent = year + '年';
                yearSelect.appendChild(option);
            }
            yearSelect.value = currentYear;
            monthSelect.value = today.getMonth() + 1;
        }
        
        // 设置自定义报告默认日期范围
        const startDateInput = document.getElementById('customReportStartDate');
        const endDateInput = document.getElementById('customReportEndDate');
        if (startDateInput && endDateInput) {
            startDateInput.value = today.toISOString().split('T')[0];
            const endDate = new Date(today);
            endDate.setDate(today.getDate() + 30);
            endDateInput.value = endDate.toISOString().split('T')[0];
        }
    }

    // 显示模态框
    function showModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.remove('hidden');
        }
    }

    // 隐藏模态框
    function hideModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('hidden');
        }
    }

    // 显示日报生成模态框
    function showDailyReportModal() {
        showModal('dailyReportModal');
    }

    // 显示周报生成模态框
    function showWeeklyReportModal() {
        showModal('weeklyReportModal');
    }

    // 显示月报生成模态框
    function showMonthlyReportModal() {
        showModal('monthlyReportModal');
    }

    // 显示自定义报告生成模态框
    function showCustomReportModal() {
        showModal('customReportModal');
    }

    // 加载AI模板
    async function loadAITemplates() {
        try {
            const response = await fetch('/api/reports/ai-templates', {
                headers: {
                    'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                }
            });
            
            if (response.ok) {
                const data = await response.json();
                renderAITemplates(data.templates || []);
            } else {
                showToast('加载AI模板失败', 'error');
            }
        } catch (error) {
            console.error('加载AI模板失败:', error);
            showToast('加载AI模板失败', 'error');
        }
    }

    // 渲染AI模板
    function renderAITemplates(templates) {
        const container = document.getElementById('aiTemplates');
        if (!container) return;
        
        container.innerHTML = '';
        
        templates.forEach(template => {
            const templateCard = document.createElement('div');
            templateCard.className = 'border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer';
            templateCard.onclick = () => useTemplate(template);
            
            templateCard.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-semibold text-gray-800">${template.name || '未命名模板'}</h4>
                    <span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">AI</span>
                </div>
                <p class="text-gray-600 text-sm mb-3">${template.description || '无描述'}</p>
                <div class="flex flex-wrap gap-1">
                    ${(template.sections || []).map(section => 
                        `<span class="bg-gray-100 text-gray-700 text-xs px-2 py-1 rounded">${section}</span>`
                    ).join('')}
                </div>
            `;
            
            container.appendChild(templateCard);
        });
    }

    // 使用模板
    function useTemplate(template) {
        if (!template) return;
        
        if (template.report_type === 'custom') {
            showCustomReportModal();
            const titleInput = document.getElementById('customReportTitle');
            if (titleInput) {
                titleInput.value = (template.name || '').replace('AI', '');
            }
            
            // 设置章节选择
            const checkboxes = document.querySelectorAll('#customReportForm input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = (template.sections || []).includes(checkbox.value);
            });
        } else if (template.report_type === 'daily') {
            showDailyReportModal();
        } else if (template.report_type === 'weekly') {
            showWeeklyReportModal();
        } else if (template.report_type === 'monthly') {
            showMonthlyReportModal();
        }
    }

    // 加载报告列表
    async function loadReports(page = 1) {
        try {
            const reportType = document.getElementById('reportTypeFilter')?.value || '';
            const status = document.getElementById('reportStatusFilter')?.value || '';
            
            let url = `/api/reports/?page=${page}&page_size=10`;
            if (reportType) url += `&report_type=${reportType}`;
            if (status) url += `&status=${status}`;
            
            const response = await fetch(url, {
                headers: {
                    'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                }
            });
            
            if (response.ok) {
                const data = await response.json();
                renderReports(data.items || []);
                renderPagination(data.total_pages || 1, page);
            } else {
                showToast('加载报告列表失败', 'error');
            }
        } catch (error) {
            console.error('加载报告列表失败:', error);
            showToast('加载报告列表失败', 'error');
        }
    }

    // 渲染报告列表
    function renderReports(reports) {
        const tbody = document.getElementById('reportsTableBody');
        if (!tbody) return;
        
        tbody.innerHTML = '';
        
        reports.forEach(report => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50';
            
            const statusClass = {
                'generating': 'bg-yellow-100 text-yellow-800',
                'completed': 'bg-green-100 text-green-800',
                'failed': 'bg-red-100 text-red-800'
            }[report.status] || 'bg-gray-100 text-gray-800';
            
            const statusText = {
                'generating': '生成中',
                'completed': '已完成',
                'failed': '失败'
            }[report.status] || report.status;
            
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm font-medium text-gray-900">${report.title || '未命名报告'}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="text-sm text-gray-900">${getReportTypeText(report.report_type)}</span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusClass}">
                        ${statusText}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${report.created_at ? new Date(report.created_at).toLocaleString('zh-CN') : ''}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button onclick="viewReport(${report.id})" class="text-blue-600 hover:text-blue-900 mr-2">查看</button>
                    ${report.status === 'completed' ? `<button onclick="downloadReport(${report.id})" class="text-green-600 hover:text-green-900 mr-2">下载</button>` : ''}
                    <button onclick="deleteReport(${report.id})" class="text-red-600 hover:text-red-900">删除</button>
                </td>
            `;
            
            tbody.appendChild(row);
        });
    }

    // 获取报告类型文本
    function getReportTypeText(type) {
        const typeMap = {
            'daily': '日报',
            'weekly': '周报',
            'monthly': '月报',
            'custom': '自定义'
        };
        return typeMap[type] || type;
    }

    // 渲染分页
    function renderPagination(totalPages, currentPage) {
        const pagination = document.getElementById('pagination');
        if (!pagination) return;
        
        pagination.innerHTML = '';
        
        if (totalPages <= 1) return;
        
        const paginationHtml = document.createElement('div');
        paginationHtml.className = 'flex space-x-2';
        
        // 上一页
        if (currentPage > 1) {
            const prevBtn = document.createElement('button');
            prevBtn.className = 'px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50';
            prevBtn.textContent = '上一页';
            prevBtn.onclick = () => loadReports(currentPage - 1);
            paginationHtml.appendChild(prevBtn);
        }
        
        // 页码
        for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-2 border border-gray-300 rounded-md ${i === currentPage ? 'bg-blue-500 text-white' : 'bg-white hover:bg-gray-50'}`;
            pageBtn.textContent = i;
            pageBtn.onclick = () => loadReports(i);
            paginationHtml.appendChild(pageBtn);
        }
        
        // 下一页
        if (currentPage < totalPages) {
            const nextBtn = document.createElement('button');
            nextBtn.className = 'px-3 py-2 bg-white border border-gray-300 rounded-md hover:bg-gray-50';
            nextBtn.textContent = '下一页';
            nextBtn.onclick = () => loadReports(currentPage + 1);
            paginationHtml.appendChild(nextBtn);
        }
        
        pagination.appendChild(paginationHtml);
    }

    // 查看报告
    async function viewReport(reportId) {
        try {
            const response = await fetch(`/api/reports/${reportId}/ai-content`, {
                headers: {
                    'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                }
            });
            
            if (response.ok) {
                const data = await response.json();
                showReportDetail(data);
            } else {
                showToast('加载报告内容失败', 'error');
            }
        } catch (error) {
            console.error('加载报告内容失败:', error);
            showToast('加载报告内容失败', 'error');
        }
    }

    // 显示报告详情
    function showReportDetail(reportData) {
        const content = document.getElementById('reportDetailContent');
        if (!content) return;
        
        content.innerHTML = `
            <div class="mb-6">
                <h2 class="text-2xl font-bold text-gray-800 mb-2">${reportData.title || '未命名报告'}</h2>
                <p class="text-gray-600">生成时间: ${reportData.generated_at ? new Date(reportData.generated_at).toLocaleString('zh-CN') : ''}</p>
            </div>
            <div class="prose max-w-none">
                <div class="whitespace-pre-wrap text-gray-800">${reportData.content || '无内容'}</div>
            </div>
        `;
        showModal('reportDetailModal');
    }

    // 下载报告
    function downloadReport(reportId) {
        showToast('下载功能开发中', 'info');
    }

    // 删除报告
    async function deleteReport(reportId) {
        if (!confirm('确定要删除这个报告吗？')) {
            return;
        }
        
        try {
            const response = await fetch(`/api/reports/${reportId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                }
            });
            
            if (response.ok) {
                showToast('报告删除成功', 'success');
                loadReports();
            } else {
                showToast('删除报告失败', 'error');
            }
        } catch (error) {
            console.error('删除报告失败:', error);
            showToast('删除报告失败', 'error');
        }
    }

    // 表单提交处理
    function setupFormHandlers() {
        // 日报表单
        const dailyForm = document.getElementById('dailyReportForm');
        if (dailyForm) {
            dailyForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = {
                    report_date: document.getElementById('dailyReportDate')?.value || ''
                };
                
                try {
                    showLoading('正在生成AI日报...');
                    const response = await fetch('/api/reports/generate/daily', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                        },
                        body: JSON.stringify(formData)
                    });
                    
                    if (response.ok) {
                        showToast('AI日报生成任务已启动', 'success');
                        hideModal('dailyReportModal');
                        loadReports();
                    } else {
                        showToast('生成AI日报失败', 'error');
                    }
                } catch (error) {
                    console.error('生成AI日报失败:', error);
                    showToast('生成AI日报失败', 'error');
                } finally {
                    hideLoading();
                }
            });
        }

        // 周报表单
        const weeklyForm = document.getElementById('weeklyReportForm');
        if (weeklyForm) {
            weeklyForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = {
                    week_start: document.getElementById('weeklyReportDate')?.value || ''
                };
                
                try {
                    showLoading('正在生成AI周报...');
                    const response = await fetch('/api/reports/generate/weekly', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                        },
                        body: JSON.stringify(formData)
                    });
                    
                    if (response.ok) {
                        showToast('AI周报生成任务已启动', 'success');
                        hideModal('weeklyReportModal');
                        loadReports();
                    } else {
                        showToast('生成AI周报失败', 'error');
                    }
                } catch (error) {
                    console.error('生成AI周报失败:', error);
                    showToast('生成AI周报失败', 'error');
                } finally {
                    hideLoading();
                }
            });
        }

        // 月报表单
        const monthlyForm = document.getElementById('monthlyReportForm');
        if (monthlyForm) {
            monthlyForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const formData = {
                    year: parseInt(document.getElementById('monthlyReportYear')?.value || '2024'),
                    month: parseInt(document.getElementById('monthlyReportMonth')?.value || '1')
                };
                
                try {
                    showLoading('正在生成AI月报...');
                    const response = await fetch('/api/reports/generate/monthly', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                        },
                        body: JSON.stringify(formData)
                    });
                    
                    if (response.ok) {
                        showToast('AI月报生成任务已启动', 'success');
                        hideModal('monthlyReportModal');
                        loadReports();
                    } else {
                        showToast('生成AI月报失败', 'error');
                    }
                } catch (error) {
                    console.error('生成AI月报失败:', error);
                    showToast('生成AI月报失败', 'error');
                } finally {
                    hideLoading();
                }
            });
        }

        // 自定义报告表单
        const customForm = document.getElementById('customReportForm');
        if (customForm) {
            customForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                const checkboxes = document.querySelectorAll('#customReportForm input[type="checkbox"]:checked');
                const sections = Array.from(checkboxes).map(cb => cb.value);
                
                const formData = {
                    title: document.getElementById('customReportTitle')?.value || '',
                    start_date: document.getElementById('customReportStartDate')?.value || '',
                    end_date: document.getElementById('customReportEndDate')?.value || '',
                    sections: sections
                };
                
                try {
                    showLoading('正在生成AI自定义报告...');
                    const response = await fetch('/api/reports/generate/custom', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + (localStorage.getItem('auth_token') || '')
                        },
                        body: JSON.stringify(formData)
                    });
                    
                    if (response.ok) {
                        showToast('AI自定义报告生成任务已启动', 'success');
                        hideModal('customReportModal');
                        loadReports();
                    } else {
                        showToast('生成AI自定义报告失败', 'error');
                    }
                } catch (error) {
                    console.error('生成AI自定义报告失败:', error);
                    showToast('生成AI自定义报告失败', 'error');
                } finally {
                    hideLoading();
                }
            });
        }

        // 筛选器变化时重新加载
        const reportTypeFilter = document.getElementById('reportTypeFilter');
        const reportStatusFilter = document.getElementById('reportStatusFilter');
        
        if (reportTypeFilter) {
            reportTypeFilter.addEventListener('change', () => loadReports(1));
        }
        if (reportStatusFilter) {
            reportStatusFilter.addEventListener('change', () => loadReports(1));
        }
    }

    // 设置表单处理器
    setupFormHandlers();
</script>
{% endblock %}